/*
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

/* Author: Jorge Peña */

#include "xineramoid.h"
#include "screens.h"

#include <QtGui>
#include <QPainter>
#include <QFontMetrics>
#include <QSizeF>
 
#include <Plasma/Svg>
#include <Plasma/Theme>
#include <KConfigDialog>
#include <KConfigGroup>

 
PlasmaXineramoid::PlasmaXineramoid(QObject *parent, const QVariantList &args)
    : Plasma::Applet(parent, args)
    , m_svg(this)
    , m_icon("document")
    , numScreens(0)
    , setup(NULL)
{
    m_svg.setImagePath("widgets/background");
    // Establecerá el fondo por defecto del applet, gratis!
    setBackgroundHints(DefaultBackground);
    resize(200, 200);
    Plasma::DataEngine *engine;
    engine = dataEngine("xrandr");
    if (!engine->isValid()){
        qDebug() << "XRandR-Engine is not running";
    }
    engine->connectSource("Virtual Desktop",this);
    //engine->connectSource("Screens",this,5000);
}
 
 
PlasmaXineramoid::~PlasmaXineramoid()
{
    if (hasFailedToLaunch()) {
        // Hacer algo de limpieza aquí
    } else {
        // Guardar la configuracion
    }
}
 
void PlasmaXineramoid::init()
{
    loadConfig();
    // Una pequeña demostracion de la función setFailedToLaunch
    if (m_icon.isNull()) {
        setFailedToLaunch(true, i18n("Icon doesn't exit"));
    }
} 
 
 
void PlasmaXineramoid::paintInterface(QPainter *p,
        const QStyleOptionGraphicsItem *option, const QRect &contentsRect)
{
    Q_UNUSED(option);
    p->setRenderHint(QPainter::SmoothPixmapTransform);
    p->setRenderHint(QPainter::Antialiasing);
    
	Plasma::Svg icon_main;
	icon_main.setImagePath("widgets/lcd");
	QSize size_main = icon_main.size();
    size_main.scale(contentsRect.width(), contentsRect.height(), Qt::KeepAspectRatio);
    icon_main.resize(size_main);

    icon_main.paint(p, 12, 15);
    
    p->save();
    p->setPen(Qt::white);
    p->drawText(contentsRect, Qt::AlignVCenter | Qt::AlignHCenter, QString("%1").arg(numScreens));
    p->restore();
}

//void PlasmaXineramoid::mousePressEvent(QGraphicsSceneMouseEvent *event){
//    Q_UNUSED(event);
//}

void PlasmaXineramoid::createConfigurationInterface(KConfigDialog *parent){
    //Check for memory leaks
    parent->setButtons( KDialog::Ok|KDialog::Cancel|KDialog::Apply );
    
    //Create graphical setup
    QGraphicsScene *scene = new QGraphicsScene(0,0,maxWidth,maxHeight);
    setup->draw(scene);

    QWidget *page = new QWidget();
    QGraphicsView *view = new QGraphicsView(scene);
    QLabel *lblXRandrOptions = new QLabel( i18n("XRandr Options"), page );
    txtXRandrOptions = new QLineEdit();
    txtXRandrOptions->setText(xrandrArgs);

    QVBoxLayout *mainLayout = new QVBoxLayout( page );
    mainLayout->addWidget(view);
    mainLayout->addWidget(lblXRandrOptions);
    mainLayout->addWidget(txtXRandrOptions);
    mainLayout->addStretch();
    parent->addPage( page, i18nc( "name of the applet", "%1 Settings", name() ), icon() );

    view->fitInView(0,0,maxWidth,maxHeight);
    view->show();

    connect(parent, SIGNAL(okClicked()), this, SLOT( saveConfig() ));
    connect(parent, SIGNAL(okClicked()), this, SLOT( scene_disconnect() ));
    connect(parent, SIGNAL(cancelClicked()), this, SLOT( scene_disconnect() ));
    connect(scene,SIGNAL(changed(const QList<QRectF> &)), this, SLOT( sceneChanged()));
    connect(txtXRandrOptions,SIGNAL(textEdited(const QString &)), this, SLOT( textChanged()));
}

void PlasmaXineramoid::dataUpdated(const QString &name, const Plasma::DataEngine::Data &data){
    if (name == "Screens"){
        int num = data["Detected Screens"].toInt();
        if (num != numScreens){
            if (setup) delete setup;
            setup = new Setup(data["Identifier"].toString(),
                    maxWidth,maxHeight);
            KConfigGroup cfg = config();
            xrandrArgs = cfg.readEntry(setup->id());
            if (xrandrArgs == ""){
                xrandrArgs = setup->bestSetup();
            }else{
                setup->loadSetup(xrandrArgs);
            }
            if (system(xrandrArgs.toAscii()))
            {
                perror("Failed to Set Screen\n");
            }

            numScreens = num;
            emit monitorChanged();
            update();
        }
    }
    else if( name == "Virtual Desktop" ){
        maxWidth = data["Width"].toInt();
        maxHeight = data["Height"].toInt();
        dataEngine("xrandr")->connectSource("Screens",this,5000);
    }
}

void PlasmaXineramoid::sceneChanged(){
   if (setup){
       txtXRandrOptions->setText(setup->setup());
       setup->loadSetup(txtXRandrOptions->text());
       txtXRandrOptions->setText(setup->setup());
   }
}
void PlasmaXineramoid::textChanged(){
   if (setup){
       setup->loadSetup(txtXRandrOptions->text());
    }
}

void PlasmaXineramoid::loadConfig(){
    KConfigGroup cfg = config();
    //xrandrArgs = cfg.readEntry(setup->id());
}
void PlasmaXineramoid::saveConfig(){
    KConfigGroup cfg = config();
    cfg.writeEntry(setup->id(),txtXRandrOptions->text());
    xrandrArgs = txtXRandrOptions->text();
    cfg.sync();
}

void PlasmaXineramoid::scene_disconnect(){
    disconnect(this, SLOT( sceneChanged()));
    disconnect(this, SLOT( textChanged()));
}
 
#include "xineramoid.moc"
